package com.legendframework.core;

import com.legendframework.core.ioc.impl.ComponentBeansGenerate;
import com.legendframework.core.cmd.paramer.converter.ConverterInstanceSuccessHandle;
import com.legendframework.core.dao.sql.pool.WhiteDataSource;
import com.legendframework.core.support.lang3.StringUtils;
import org.yaml.snakeyaml.Yaml;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * 抽象的主类
 *
 * @author 196
 **/
public abstract class LegendPlugin extends AbstractLegendPlugin {

    /**
     * 初始化主类
     */
    protected void init() {
        store.build();
    }

    @Override
    protected Store createStore() {
        return new Store(this);
    }

    /**
     * 注册指令参数转换器
     */
    private void registerComponentHandle(){
        //注入处理器
        ComponentBeansGenerate beansGenerate = this.store.getBeansFactoryManager().getBeansGenerate(ComponentBeansGenerate.class);
        if (beansGenerate != null) {
            beansGenerate.addSuccessHandle(new ConverterInstanceSuccessHandle());
        }
    }

    @Override
    public void onLoad() {
        //注册指令参数转换器
        registerComponentHandle();
        super.onLoad();
    }

    /**
     * 插件被Bukkit启用的时候执行
     */
    @Override
    public void onEnable() {
        init();
        //注册指令
        registerCommand();
        start();
    }

    @Override
    public String getSavePath() {
        //根据plugin.yml文件获取配置文件的保存路径，如果没有则取默认
        JarFile jar = null;
        try {
            jar = new JarFile(this.getFile());
            JarEntry entry = jar.getJarEntry("plugin.yml");
            Yaml yaml = new Yaml();
            Map result = yaml.load(jar.getInputStream(entry));
            Object configPath = result.get("configPath");
            if (configPath instanceof String && StringUtils.isNotEmpty((CharSequence) configPath)) {
                return (String) configPath;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return super.getSavePath();
    }

    /**
     * 插件被Bukkit卸载的时候执行
     */
    @Override
    public void onDisable() {
        //销毁数据源
        if (store.getDataResources() != null && store.getDataResources().getDataSource() instanceof WhiteDataSource) {
            ((WhiteDataSource) store.getDataResources().getDataSource()).discard();
        }
        end();
    }
}
